﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FileMonitor.Service.ProcessMonitor.Contract;
using FileMonitor.Service.ProcessMonitor.Model;
using FileMonitor.Service.Provider.FileMonitor;
using System.ServiceModel;


namespace FileMonitor.Client
{
    public partial class Form1 : Form
    {
        Dictionary<string, MonitorProcessInfo> listMis;
        public Form1()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            string[] allEndPonits = System.Configuration.ConfigurationManager.AppSettings["endPonits"].Split(",".ToCharArray());
            foreach (string str in allEndPonits)
            {
                this.listEndPoints.Items.Add(str);
            }
           // this.listEndPoints.DataSource = allEndPonits.ToList();
            if (this.listEndPoints.Items.Count > 0)
            {
                this.listEndPoints.SelectedIndex = 0;
            }
        }

 
        private void GetProcessInfo(string endPointName)
        {
            string currentEndPointName = this.listEndPoints.SelectedItem.ToString();
            using (ChannelFactory<IMonitorProcessService> channelFactory = new ChannelFactory<IMonitorProcessService>(currentEndPointName))
            {
                IMonitorProcessService channel = channelFactory.CreateChannel();
                listMis = channel.GetAllProcessInfo();
            }
        }

        private void BindProcessInfo()
        {
            string currentEndPointName = this.listEndPoints.SelectedItem.ToString();
            GetProcessInfo(currentEndPointName);
            this.tabMain.TabPages.Clear();
            foreach (MonitorProcessInfo mi in this.listMis.Values)
            {
                ProcessForm process = new ProcessForm();
                process.Initialize(mi,this.listEndPoints.SelectedItem.ToString());
                TabPage tab=new TabPage(mi.ProcessName);
                tab.Controls.Add(process);
                this.tabMain.TabPages.Add(tab);
            }
        }

        private void btnMonitor_Click(object sender, EventArgs e)
        {
            BindProcessInfo();
        }

        private void btnRefreshService_Click(object sender, EventArgs e)
        {
            string currentEndPointName = this.listEndPoints.SelectedItem.ToString();
            using (ChannelFactory<IMonitorProcessService> channelFactory = new ChannelFactory<IMonitorProcessService>(currentEndPointName))
            {
                IMonitorProcessService channel = channelFactory.CreateChannel();
                channel.RefreshProcesses();
            }
            BindProcessInfo();
        }

      
    }
}
